-- UISkillLearn
-- Created by chengb Mar/31/2015
-- 技能学习界面

require "game/ui/form/hero/UILearnNewSkillEffect"

UISkillLearn = class("UISkillLearn", function()
    return cc.Layer:create();
end);

function UISkillLearn.create(careerList)
    return UISkillLearn.new(careerList);
end

-- 最多可显示星星数
local MAX_STAR_NUM = 5;

-- 属性半透明度
local ATTRIB_OPACITY_VALUE = 100;

-- 内部函数声明
local resize;

function UISkillLearn:ctor(careerList)
    -- 初始化
    self:setName("UISkillLearn");
    local node = cc.CSLoader:createNode("layout/hero/SkillLearn.csb");
    self:addChild(node);
    self.node = node;

    -- 必须有可学的职业
    assert(careerList, "可学的职业不能为空。");

    -- 获取本次可学习的职业
    self.newCareerList = careerList;

    local pet = ME.user:getActivePet();
    self.pet = pet;

    -- 默认选中第一个
    self.selectIndex = 1;

    -- 需要显示在头部菜单上面
    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    local delay = 0.8;
    if DungeonGuideM.isGuideFinished() then
        delay = 0.1;
    end

    -- 注册点击事件
    performWithDelay(self, function() self:registerTouchEvent(); end, delay);

    -- 初始化窗口
    self:initForm();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化窗口
function UISkillLearn:initForm()
    local skillPanel = findChildByName(self.node, "CT/skill_panel");
    local panelWidth  = skillPanel:getContentSize().width;
    local panelHeight = skillPanel:getContentSize().height;

    -- 图标间距
    local gap = 50;

    -- 可选职业个数
    local count = #self.newCareerList;

    -- 图标宽、高
    local iconWidth  = 180;
    local iconHeight = 180;

    self.childList = {};

    local careerCount = #self.newCareerList;
    local letterCount = nil;

    if careerCount > 1 then
        letterCount = 8;
    end

    for i, newCareer in pairs(self.newCareerList) do
        local child = cc.CSLoader:createNode("layout/hero/SkillIcon2.csb");
        skillPanel:addChild(child);
        child:setTag(i);

        table.insert(self.childList, child);

        -- 计算图标与容器的边距
        local margin = (panelWidth - (count * iconWidth + (count - 1) * gap))/2;
        local posX =  margin + (i - 1) * (iconWidth + gap) + iconWidth/2;
        child:setPosition(posX, panelHeight/2);

        local careerInfo = CareerM.getCareerInfo(newCareer);

        local iconImg   = findChildByName(child, "icon");
        local nameLabel = findChildByName(child, "name");
        local kerning = -2;
        if getLang() ~= "zh" and getLang() ~= "tw" then
            kerning = -2;
        end
        iconImg:loadTexture(getCareerIconPath(careerInfo["icon"]));
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true, kerning, nil, nil, letterCount, nil, true);
        nameLabel:setString(careerInfo["name"]);

        -- 默认隐藏选中光效
        local light = findChildByName(child, "light");
        light:setVisible(false);

        -- 记录箭头的初始纵坐标
        local arow = findChildByName(child, "arow");
        arow.initPosY = arow:getPositionY();

        -- 注册技能图标点击事件
        iconImg:setTouchEnabled(true);
        local function onIconClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 设置选中效果
                self:selectSkill(i);
            end
        end
        iconImg:addTouchEventListener(onIconClick);
    end

    -- 初始化特效节点

    local basePropNode = findChildByName(self.node, "CT/base_prop_node");

    -- 攻击
    local effectNode = findChildByName(basePropNode, "attack_node/effect_node");
    playAttribSparkEffect(effectNode, 1133);
    effectNode:setVisible(false);

    -- 生命
    effectNode = findChildByName(basePropNode, "hp_node/effect_node");
    playAttribSparkEffect(effectNode, 1133);
    effectNode:setVisible(false);

    -- 魔力
    effectNode = findChildByName(basePropNode, "magic_node/effect_node");
    playAttribSparkEffect(effectNode, 1133);
    effectNode:setVisible(false);

    -- 魔法
    effectNode = findChildByName(basePropNode, "mp_node/effect_node");
    playAttribSparkEffect(effectNode, 1133);
    effectNode:setVisible(false);
end

-- 选中技能
function UISkillLearn:selectSkill(index)
    if index == self.selectIndex then
        -- 选中的还是原来的技能，不处理
        return;
    end

    if index then
        self.selectIndex = index;
    end

    for _, child in pairs(self.childList) do
        local light = findChildByName(child, "light");
        local arow  = findChildByName(child, "arow");
        local icon  = findChildByName(child, "icon");
        if child:getTag() == self.selectIndex then
            light:setVisible(true);
            arow:setVisible(true);

            -- 退出灰化模式
            setGrayMode(icon, false);

            -- 旋转光圈
            light:stopAllActions();
            local actionBy = cc.RotateBy:create(30, 360);
            local sequenceAction = cc.Sequence:create(actionBy);
            light:runAction(cc.RepeatForever:create(sequenceAction));

            -- 上下跳动箭头
            local function moveItem()

                local function doItemMove()
                    local moveUp = cc.MoveTo:create(1, cc.p(arow:getPositionX(), arow.initPosY + 15));
                    local moveDown = cc.MoveTo:create(1, cc.p(arow:getPositionX(), arow.initPosY));
                    local function moveDone()
                        performWithDelay(arow, doItemMove, 0.2);
                    end

                    local callFunc = cc.CallFunc:create(moveDone);
                    arow:stopAllActions();
                    arow:runAction(cc.Sequence:create(moveUp, moveDown, callFunc));
                end

                doItemMove();
            end
            arow:stopAllActions();
            performWithDelay(arow, moveItem, 0.1);

        else
            arow:setPositionY(arow.initPosY);
            light:setVisible(false);
            arow:setVisible(false);

            -- 图标灰化处理
            setGrayMode(icon, true);
        end
    end

    -- 重绘选中的技能
    self:redrawSelectSkill();
end

-- 重绘
function UISkillLearn:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    titleLabel:setString(getLocStr("learn_skill_title"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 重绘按钮
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    local btnOk = findChildByName(self.node, "CT/btn_ok");
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_learn_skill"));

    -- 重绘选中的技能信息
    self:selectSkill();

    -- 显示当前探索点
    local spNode = findChildByName(self.node, "BT/sp_node");
    local iconImg = findChildByName(spNode, "icon");
    local icon = FieldsM.query("search_point", "icon");
    iconImg:loadTexture(getSmallAttribIconPath(icon));
    local amountLabel = findChildByName(spNode, "amount");
    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BRIGHT_YELLOW, true, -2);
    amountLabel:setString(tonumber(ME.user:queryAttrib("search_point")));
end

-- 重绘选中的技能信息
function UISkillLearn:redrawSelectSkill()
    local careerId = self.newCareerList[self.selectIndex];
    local careerInfo = CareerM.getCareerInfo(careerId);

    -- 显示bar中的职业名称和星级
    local careerNameLabel = findChildByName(self.node, "CT/bar/skill_name");
    TextStyleM.setTextStyle(careerNameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    careerNameLabel:setString(careerInfo["name"]);

    local content = "";

    -- 显示属性描述
    local propLabel = findChildByName(self.node, "CT/prop_node/prop_desc");
    local propStr = CareerM.getFeatureDesc(self.pet.classId, careerId);

    content = content .. propStr .. "\n";

    -- 显示探索点消耗
    local costInfo = CareerM.calcJoinCost(self.pet.classId, careerId);
    local needSp = costInfo["search_point"];
    local costStr = string.format(getLocStr("cost_sp_format"), needSp);

    content = content .. costStr .. "\n";

    -- 显示下一阶职业
    local nextCareerList = CareerM.getCanLearnNextCareers(self.pet, careerId);
    local nameStr = "";
    for i, id in pairs(nextCareerList) do
        local name = CareerM.getCareerInfo(id, "name");
        if i < #nextCareerList then
            nameStr = nameStr .. name .. getLocStr("pause_mark");
        else
            nameStr = nameStr .. name;
        end
    end

    if nameStr ~= "" then
        local nextSkillStr = string.format(getLocStr("next_rank_skill_format"), nameStr);
        content = content .. nextSkillStr;
    end

    local kerning = 0;
    if getLang() == "fr" then
        kerning = -1;
    end
    TextStyleM.setTextStyle(propLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, nil, kerning, nil, nil, nil, TextStyleM.TEXT_SIZE_SMALL);
    applyString(propLabel, content);

    -- 获取基础属性值
    local baseProps = CareerM.getFeatureBaseProps(self.pet.classId, careerId);
    local function getPropValue(field)
        for _, arr in pairs(baseProps) do
            if arr[2] == field then
                return arr[3];
            end
        end
        return 0;
    end

    -- 显示属性
    local function showAttribValue(value, valueLabel, nameLabel, parentNode, effectNode)
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
        TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BEIGE, false, -1);
        if value <= 0 then
            -- 半透明显示
            valueLabel:setString("");
            parentNode:setOpacity(ATTRIB_OPACITY_VALUE);
            effectNode:setVisible(false);
        else
            valueLabel:setString("+" .. value);
            parentNode:setOpacity(255);

            -- 播放闪光特性
            effectNode:setVisible(true);
        end
    end

    -- 显示基础属性
    local basePropNode = findChildByName(self.node, "CT/base_prop_node");

    -- 攻击
    local attackNode = findChildByName(basePropNode, "attack_node");
    local nameLabel  = findChildByName(basePropNode, "attack_node/name");
    local valueLabel = findChildByName(basePropNode, "attack_node/value");
    local effectNode = findChildByName(basePropNode, "attack_node/effect_node");
    nameLabel:setString(getLocStr("attack"));
    local value = getPropValue("attack");
    showAttribValue(value, valueLabel, nameLabel, attackNode, effectNode);

    -- 生命
    local hpNode = findChildByName(basePropNode, "hp_node");
    nameLabel  = findChildByName(basePropNode, "hp_node/name");
    valueLabel = findChildByName(basePropNode, "hp_node/value");
    effectNode = findChildByName(basePropNode, "hp_node/effect_node");
    nameLabel:setString(getLocStr("hp"));
    local value = getPropValue("max_hp");
    showAttribValue(value, valueLabel, nameLabel, hpNode, effectNode);

    -- 魔力
    local magicNode = findChildByName(basePropNode, "magic_node");
    nameLabel  = findChildByName(basePropNode, "magic_node/name");
    valueLabel = findChildByName(basePropNode, "magic_node/value");
    effectNode = findChildByName(basePropNode, "magic_node/effect_node");
    nameLabel:setString(getLocStr("magic"));
    local value = getPropValue("magic");
    showAttribValue(value, valueLabel, nameLabel, magicNode, effectNode);

    -- 魔法
    local mpNode = findChildByName(basePropNode, "mp_node");
    nameLabel  = findChildByName(basePropNode, "mp_node/name");
    valueLabel = findChildByName(basePropNode, "mp_node/value");
    effectNode = findChildByName(basePropNode, "mp_node/effect_node");
    nameLabel:setString(getLocStr("mp"));
    local value = getPropValue("max_mp");
    showAttribValue(value, valueLabel, nameLabel, mpNode, effectNode);

    -- 显示背景称号图标
    -- 放放、半透明显示
    local bgIconImg = findChildByName(self.node, "CT/bg_icon");
    bgIconImg:loadTexture(getCareerIconPath(careerInfo["icon"]));
    bgIconImg:setScale(1.8);
    bgIconImg:setOpacity(50);
end

-- 注册点击事件
function UISkillLearn:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UISkillLearn");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册学习按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local newCareer = self.newCareerList[self.selectIndex];

            -- 判断能否学习
            local ret = CareerM.canJoin(self.pet.classId, newCareer);
            if ret ~= true then
                if type(ret) == "string" then
                    alert(ret);
                end

                return;
            end

            -- 学习
            DungeonActionM.go("join_career", self.pet.classId, newCareer);
        end
    end
    AddTouchEventListener(btnOk, onOkClick);
end

-- 注册事件处理回调函数
function UISkillLearn:registerEventCallback()
    -- 注册学习职业成功的事件回调
    EventMgr.register("UISkillLearn", event.JOIN_CAREER, function(args)
        -- 提示
        local careerId = args.careerId;
        local name = CareerM.getCareerInfo(careerId, "name");
        local msg = string.format(getLocStr("join_career_succ"), name);
        local ret = args.ret;

        -- 播放特效界面
        if UIMgr.getCurrentScene():isOpen("UILearnNewSkillEffect") then
            UIMgr.getCurrentScene():removeFormByName("UILearnNewSkillEffect");
        end
        local uiEffect = UILearnNewSkillEffect.create(careerId, ret);
        UIMgr.getCurrentScene():addForm(uiEffect);

        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UISkillLearn");
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UISkillLearn");
        end
    end);
end













